/*
 * @Author: XXX
 * @Date: 2024-04-08 15:43:13
 * @LastEditors: Please set LastEditors
 * @Description: description
 */
/**
 * @Author: HaoyangDu
 * @Email: HaoyangDu@wits.com
 * @Date: 2024-04-08 15:43:13
 * @LastEditTime: 2024-05-30 08:24:14
 * @LastEditors: your name
 * @Description: 封装网络请求
 * @FilePath: \hfxed\src\utils\service.js
 */
import config from "./config.js";
import * as utils from "./utils.js";
/**
 * @description: 封装微信post方法，并添加公共报文头
 * @param {*} targetUrl
 * @param {*} params
 * @param {*} headerConfig
 * @return {*}
 */
export function networkpost(targetUrl, params = {}, headerConfig = {}) {
  console.log("----加密前入参----", targetUrl, params);

  const url = config.url + targetUrl; // 拼接完整请求url
  const data = utils.doEncryptSM2(params); // 对请求data进行sm2加密
  const header = {
    "Content-Type": "application/json",
    channel: config.channel,
    source: config.source,
    productId: config.productId,
    productType: config.productType,
    token: wx.getStorageSync("token") ? wx.getStorageSync("token") : "",
    openid: wx.getStorageSync("openId") ? wx.getStorageSync("openId") : "",
    ...headerConfig,
  };
  console.log("----请求头----", targetUrl, header);
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: "",
      mask: true,
    });
    wx.request({
      url,
      header,
      data,
      timeout: 40000,
      method: "POST",
      success(res) {
        wx.hideLoading()
        console.log(
          "----解密后报文----",
          targetUrl,
          // JSON.parse(utils.doDecryptSM2(res))
          res.data
        );
        if (res.data.code == 200) {
          resolve(res.data);
        } else if (res.data.code == 401) {
          wx.showToast({
            title: "您的登录信息已失效，请重新登录",
            icon: "none",
            duration: 1000,
            mask: true,
          });
          setTimeout(() => {
            if (targetUrl !== "common/kaptcha") {
              wx.redirectTo({
                url: "../../packageLogin/login/login",
              });
            }
          }, 1000);
        } else {
          wx.showToast({
            title: res.data.message,
            icon: "none",
            duration: 2000,
            mask: true,
          });
        }
      },
      fail: (err) => {
        wx.hideLoading()
        if (err.errMsg == "request:fail timeout") {
          wx.showToast({
            title: "系统开小差了，请重试",
            icon: "none",
            duration: 2000,
            mask: true,
          });
        }
        reject(err);
      },
    });
  });
}
